const Usecase = require('../../shared/usecase/Usecase')
const { SystemNotFoundError } = require('../../domain/system/error')
const R = require('ramda')

class UpdateSystem extends Usecase {
  constructor({ systemRepo, database, currentUser }) {
    super()
    this.systemRepo = systemRepo
    this.sequelize = database.sequelize
    this.currentUser = currentUser
  }
  async execute(data) {
    const system = await this.systemRepo.findById(data.id)
    if (!system) throw new SystemNotFoundError(data)
    const transaction = await this.sequelize.transaction()
    try {
      Object.assign(system, R.omit(['code'], data))
      await system.validate()
      await this.systemRepo.update(system, {
        currentUser: this.currentUser,
        transaction,
      })
      await transaction.commit()
    } catch (e) {
      await transaction.rollback()
      throw e
    }
  }
}

module.exports = UpdateSystem
